package com.diploma.project.aiqiyi.common.config.feign.codec;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.QueryMapEncoder;
import feign.codec.EncodeException;

import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @author lisheng
 * @description
 * @date 2018/12/22 15:16
 * @version:
 */
public class FeignQueryMapEncoder implements QueryMapEncoder {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> encode(Object object) throws EncodeException {
        try {
            return objectMapper.convertValue(object, Map.class);
        } catch (Exception e) {
            throw new EncodeException("Failure encoding object into query map", e);
        }
    }

    public void objectMapper(ObjectMapper objectMapper) {
        FeignQueryMapEncoder.objectMapper = objectMapper;
    }
}
